package com.qidian.mespro.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.qidian.mespro.mapper.ProcessMapper;
import com.qidian.mespro.service.ProcessService;
import com.qidianit.mes.pojo.Process;
import com.qidianit.mes.pojo.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * @ author: 周晓轩
 * @ company 起点编程
 * @ time: 2025/9/17 - 16:17
 * @ Description:
 */
@Service
public class ProcessServiceImpl implements ProcessService {

    @Autowired
    private ProcessMapper processMapper;

    @Override
    public Result<PageInfo<Process>> ProcessList(Process process, int pageNum, int pageSize) {
        // 开启分页
        PageHelper.startPage(pageNum,pageSize);
        List<Process> processes = processMapper.processList(process);
        // 最终返回的是一个Result，其中的数据是PageInfo
        return Result.success(new PageInfo<>(processes));
    }

    @Override
    public Result<Process> addProcess(Process process) {
        Result<Process> existResult = selectProcessByCode(process.getProcessCode());
        if (existResult.isSuccess() && existResult.getData() != null) {
            return Result.error("工序编码已存在，新增失败");
        }
        return processMapper.addProcess(process)== 1?Result.success(process):Result.error("保存失败");
    }

    @Override
    public Result<Process> selectProcessByCode(String code) {
        return Result.success(processMapper.selectProcessByCode(code));
    }

    @Override
    public Result updateProcessById(Process process) {
        Result<Process> existResult = selectProcessByCode(process.getProcessCode());
        if (existResult.isSuccess() && existResult.getData() != null) {
            if (!existResult.getData().getId().equals(process.getId())) {
                return Result.error("工序编码已被占用，请更换");
            }
        }
        return processMapper.updateProcessById(process) == 1 ? Result.success():Result.error("编辑失败");
    }

    @Override
    public Result deleteProcessById(Long id) {
        return processMapper.deleteProcessById(id) == 1?Result.success():Result.error("删除失败");
    }

    @Override
    public Result batchDelete(Long[] ids) {
        return processMapper.batchDelete(ids) > 0?Result.success():Result.error("删除失败");
    }
}
